import React, { Component } from 'react'
import PubSub from 'pubsub-js'
import axios from 'axios'

export default class Search extends Component {
  search = async () => {
    


    // 获取用户输入
    const {keyWordElement: {value: keyWord}} = this
    // const {value} = this.keyWordElement
    console.log(keyWord)
    // console.log(this.keyWordElement.value)

    // 发送请求前 通知app 更新状态
    // this.props.updateAppState({isFirst: false, isLoading: true})
    PubSub.publish('gzt', {isFirst: false, isLoading: true})
    // 发送网络请求(未优化)
    // fetch(`http://localhost:3000/api/search/users2?q=${keyWord}`).then(
    //   response => {
    //     console.log('联系服务器成功 了', response)
    //     return response.json()
    //   },
    //   error => {
    //     console.log('联系服务器 失败了', error)
    //     return new Promise(() => {})
    //   })
    //   .then(response => {console.log('成功了', response)},
    //     error => {console.log('失败了')}
    //   )

    // 发送网络请求(未优化)
    try {
      const response = await fetch(`http://localhost:3000/api/search/users2?q=${keyWord}`)
      const data = await response.json()
      PubSub.publish('gzt', {isLoading: false, users: data.items})
      console.log(data)  
    } catch (error) {
      console.log('请求出错', error)
      PubSub.publish('gzt', {isLoading: false, err: error.message})
    }
    

    //#region  
    // axios.get(`http://localhost:3000/api/search/users?q=${keyWord}`).then(
    //   response => {
    //     console.log('成功了', response.data)
    //     // 请求成功后更新 状态
    //     // 发布消息
    //     PubSub.publish('gzt', {isLoading: false, users: response.data.items})
    //     // this.props.updateAppState({isLoading: false, users: response.data.items})
    //     // this.props.updateAppState(response.data.items)
    //   },
    //   error => {
    //     console.log('失败了', error)
    //     // 请求失败后
    //     PubSub.publish('gzt', {isLoading: false, err: error.message})
    //     // this.props.updateAppState({isLoading: false, err: error.message})
    //   }
    // )
    //#endregion
  }
  render() {
    return (
      <section className="jumbotron">
        <h3 className="jumbotron-heading">Search Github Users</h3>
        <div>
          <input ref={c => this.keyWordElement = c} type="text" placeholder="enter the name you search"/>&nbsp;
          <button onClick={this.search}>Search</button>
        </div>
      </section>
    )
  }
}
